#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N = 205, INF = 0x3f3f3f3f;
char str[N], s[N];
int p[N];
bool v[N];
int cnt;

LL gcd(LL a, LL b){
    return b == 0 ? a : gcd(b, a % b);
}

LL lcm(LL a, LL b){
    return (LL)a / gcd(a, b) * b;
}

void dfs(int i){
    if(v[i]) return;
    s[cnt ++] = str[i];
    v[i] = true;

    dfs(p[i]);
}

bool check(int fo){
    for(int k = 0; k < cnt; k ++){
        if(s[(fo + k) % cnt] != s[k]){
            return false;
        }
    }
    return true;
}
 
int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(0);
 
    int T;
    cin >> T;
    while(T--){
        int n;
        cin >> n >> str + 1;
        for(int i = 1; i <= n; i++) cin >> p[i], v[i] = 0;
        LL res = 1;
        for(int i = 1; i <= n; i++)
            if (!v[i]){
                cnt = 0;
                dfs(i);
                LL t;
                for(int k = 1; k <= cnt; k++){
                    if(check(k)){
                        t = k;
                        break;
                    }
                }
                    
                res = lcm(res, t);
            }
        cout << res << '\n';
    }
 
}